import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const username = ref(localStorage.getItem('username') || '')
  const userId = ref(parseInt(localStorage.getItem('userId') || '0'))

  const isAuthenticated = computed(() => !!token.value)

  async function login(credentials) {
    try {
      const response = await api.post('/auth/login', credentials)
      const data = response.data
      
      token.value = data.access_token
      username.value = data.username
      userId.value = data.user_id

      localStorage.setItem('token', data.access_token)
      localStorage.setItem('username', data.username)
      localStorage.setItem('userId', data.user_id.toString())

      return { success: true }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.detail || '登录失败'
      }
    }
  }

  async function register(userData) {
    try {
      const response = await api.post('/auth/register', userData)
      const data = response.data
      
      token.value = data.access_token
      username.value = data.username
      userId.value = data.user_id

      localStorage.setItem('token', data.access_token)
      localStorage.setItem('username', data.username)
      localStorage.setItem('userId', data.user_id.toString())

      return { success: true }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.detail || '注册失败'
      }
    }
  }

  function logout() {
    token.value = ''
    username.value = ''
    userId.value = 0

    localStorage.removeItem('token')
    localStorage.removeItem('username')
    localStorage.removeItem('userId')
  }

  return {
    token,
    username,
    userId,
    isAuthenticated,
    login,
    register,
    logout
  }
})
